<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no, maximum-scale=1.0, minimum-scale=1.0">
    <title>Konva.js 手写板</title>
    <script src="https://unpkg.com/konva@9/konva.min.js"></script>
    <style>
        body {
            margin: 0;
            padding: 10px;
            font-family: 'Microsoft YaHei', sans-serif;
            background-color: #f0f0f0;
            overflow-x: hidden;
            touch-action: none;
        }
        
        @media (max-width: 768px) {
            body {
                padding: 5px;
            }
        }
        
        .toolbar {
            display: flex;
            align-items: center;
            gap: 15px;
            margin-bottom: 20px;
            padding: 15px;
            background-color: white;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            flex-wrap: wrap;
        }
        
        @media (max-width: 768px) {
            .toolbar {
                gap: 8px;
                padding: 10px;
                margin-bottom: 10px;
            }
        }
        
        .tool-group {
            display: flex;
            align-items: center;
            gap: 10px;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 5px;
            flex-wrap: wrap;
        }
        
        @media (max-width: 768px) {
            .tool-group {
                gap: 5px;
                padding: 8px;
                min-width: 0;
            }
        }
        
        .tool-group label {
            font-weight: bold;
            color: #333;
        }
        
        .color-picker {
            width: 40px;
            height: 40px;
            border: none;
            border-radius: 5px;
            cursor: pointer;
        }
        
        .brush-size {
            width: 100px;
        }
        
        .tool-button {
            padding: 8px 16px;
            font-size: 14px;
            border: 2px solid #007bff;
            background-color: white;
            color: #007bff;
            border-radius: 5px;
            cursor: pointer;
            transition: all 0.3s;
            user-select: none;
            -webkit-tap-highlight-color: transparent;
        }
        
        @media (max-width: 768px) {
            .tool-button {
                padding: 10px 12px;
                font-size: 12px;
                min-width: 60px;
                min-height: 40px;
            }
        }
        
        .tool-button.active {
            background-color: #007bff;
            color: white;
        }
        
        .tool-button:hover {
            background-color: #0056b3;
            color: white;
            border-color: #0056b3;
        }
        
        .tool-button:disabled {
            background-color: #e9ecef;
            color: #6c757d;
            border-color: #dee2e6;
            cursor: not-allowed;
        }
        
        .tool-button:disabled:hover {
            background-color: #e9ecef;
            color: #6c757d;
            border-color: #dee2e6;
        }
        
        .canvas-container {
            background-color: white;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            display: inline-block;
            max-width: 100%;
            overflow: hidden;
        }
        
        @media (max-width: 768px) {
            .canvas-container {
                width: 100%;
                max-width: 100vw;
            }
        }
        
        .info-panel {
            margin-top: 20px;
            padding: 15px;
            background-color: white;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        
        @media (max-width: 768px) {
            .info-panel {
                margin-top: 10px;
                padding: 10px;
                font-size: 12px;
            }
            
            .info-panel h3 {
                font-size: 16px;
            }
            
            .info-panel li {
                margin: 3px 0;
            }
        }
        
        .info-panel h3 {
            margin-top: 0;
            color: #333;
        }
        
        .info-panel ul {
            margin: 10px 0;
            padding-left: 20px;
        }
        
        .info-panel li {
            margin: 5px 0;
            color: #666;
        }
        
        /* 文字输入框样式 */
        .text-input-overlay {
            position: absolute;
            background: white;
            border: 2px solid #999;
            border-radius: 3px;
            padding: 2px;
            z-index: 1000;
            box-shadow: 0 2px 10px rgba(0,0,0,0.2);
        }
        
        .text-input-overlay input {
            width: 100%;
            border: none;
            outline: none;
            font-size: 16px;
            font-family: 'Microsoft YaHei';
            background: transparent;
            padding: 0;
            margin: 0;
            line-height: 1.2;
        }
        
        /* 移除不需要的CSS样式，因为按钮将在canvas中绘制 */
    </style>
</head>
<body>
    <div class="toolbar">
        <div class="tool-group">
            <label>工具:</label>
            <button class="tool-button active" onclick="setTool('brush')">画笔</button>
            <button class="tool-button" onclick="setTool('polygon')">多边形</button>
            <button class="tool-button" onclick="setTool('eraser')">橡皮擦</button>
            <button class="tool-button" onclick="setTool('select')">框选</button>
            <button class="tool-button" onclick="setTool('text')">文字</button>
        </div>
        
        <div class="tool-group" id="shapeGroup" style="display: none;">
            <label>图形:</label>
            <button class="tool-button" onclick="drawPresetShape('square')">正方形</button>
            <button class="tool-button" onclick="drawPresetShape('triangle')">三角形</button>
            <button class="tool-button" onclick="drawPresetShape('star')">五角星</button>
            <button class="tool-button" onclick="drawPresetShape('circle')">圆形</button>
        </div>
        
        <div class="tool-group">
            <label>颜色:</label>
            <input type="color" class="color-picker" id="colorPicker" value="#000000" onchange="updateColor()">
        </div>
        
        <div class="tool-group">
            <label>粗细:</label>
            <input type="range" class="brush-size" id="brushSize" min="1" max="50" value="5" onchange="updateBrushSize()">
            <span id="brushSizeValue">5</span>
        </div>
        
        <div class="tool-group">
            <button class="tool-button" onclick="clearCanvas()">清空画布</button>
            <button class="tool-button" id="undoBtn" onclick="undo()" disabled>撤销</button>
            <button class="tool-button" id="redoBtn" onclick="redo()" disabled>重做</button>
            <button class="tool-button" id="deleteBtn" onclick="deleteSelectedShapes()" style="display: none; background-color: #dc3545; border-color: #dc3545; color: white;">删除选中</button>
        </div>
    </div>
    
    <div class="canvas-container">
        <div id="container"></div>
    </div>
    
    <div class="info-panel">
        <h3>使用说明</h3>
        <ul>
            <li><strong>画笔模式</strong>: 自由绘制线条</li>
            <li><strong>多边形模式</strong>: 点击添加顶点，双击完成绘制，或选择预设图形</li>
            <li><strong>橡皮擦模式</strong>: 擦除经过的区域（类似真实橡皮擦）</li>
            <li><strong>框选模式</strong>: 拖拽选择区域，点击"删除选中"按钮删除选中元素</li>
            <li><strong>文字模式</strong>: 点击画布添加文字，点击文字显示编辑/删除按钮</li>
            <li><strong>颜色选择</strong>: 点击颜色选择器更改画笔颜色</li>
            <li><strong>粗细调节</strong>: 使用滑块调节画笔粗细</li>
            <li><strong>撤销/重做</strong>: 点击按钮或使用快捷键 Ctrl+Z / Ctrl+Y</li>
        </ul>
    </div>

    <script>
        // 初始化变量
        let stage, layer, backgroundLayer;
        let currentTool = 'brush';
        let isDrawing = false;
        let isErasing = false;
        let isSelecting = false;
        let currentColor = '#000000';
        let currentBrushSize = 5;
        let polygonPoints = [];
        let polygonLine;
        let selectionRect;
        let selectedShapes = [];
        let history = [];
        let historyIndex = -1;
        let maxHistorySize = 50; // 最大历史记录数量
        let shapeIdCounter = 0; // 形状ID计数器
        let textElements = []; // 文字元素数组
        let currentTextInput = null; // 当前文字输入框
        let isTextEditing = false; // 是否正在编辑文字
        
        // 初始化画布
        function initCanvas() {
            // 获取容器尺寸
            const container = document.getElementById('container');
            const containerRect = container.getBoundingClientRect();
            
            // 计算画布尺寸
            let canvasWidth = 800;
            let canvasHeight = 600;
            
            // 移动端适配
            if (window.innerWidth <= 768) {
                canvasWidth = Math.min(window.innerWidth - 20, 800);
                canvasHeight = Math.min(window.innerHeight * 0.6, 600);
            }
            
            stage = new Konva.Stage({
                container: 'container',
                width: canvasWidth,
                height: canvasHeight
            });
            
            // 背景层
            backgroundLayer = new Konva.Layer();
            stage.add(backgroundLayer);
            
            // 绘制层
            layer = new Konva.Layer();
            stage.add(layer);
            
            // 初始化橡皮擦层
            initEraserLayer();
            
            // 添加白色背景
            const background = new Konva.Rect({
                x: 0,
                y: 0,
                width: canvasWidth,
                height: canvasHeight,
                fill: 'white'
            });
            backgroundLayer.add(background);
            
            // 绑定事件
            stage.on('mousedown touchstart', onMouseDown);
            stage.on('mousemove touchmove', onMouseMove);
            stage.on('mouseup touchend', onMouseUp);
            stage.on('click', onMouseClick);
            stage.on('dblclick', onMouseDoubleClick);
            
            // 点击画布空白区域时隐藏文字控制按钮
            stage.on('click', function(e) {
                if (e.target === stage && currentTool !== 'text') {
                    hideAllTextControls();
                }
            });
            
            // 移动端优化：防止页面滚动
            stage.on('touchstart', function(e) {
                e.evt.preventDefault();
            });
            
            stage.on('touchmove', function(e) {
                e.evt.preventDefault();
            });
            
            // 监听窗口大小变化
            window.addEventListener('resize', handleResize);
            
            // 初始化历史记录
            history = [];
            historyIndex = -1;
            
            // 初始化按钮状态
            updateUndoRedoButtons();
        }
        
        // 处理窗口大小变化
        function handleResize() {
            if (!stage) return;
            
            // 重新计算画布尺寸
            let canvasWidth = 800;
            let canvasHeight = 600;
            
            if (window.innerWidth <= 768) {
                canvasWidth = Math.min(window.innerWidth - 20, 800);
                canvasHeight = Math.min(window.innerHeight * 0.6, 600);
            }
            
            // 更新画布尺寸
            stage.width(canvasWidth);
            stage.height(canvasHeight);
            
            // 更新背景尺寸
            const background = backgroundLayer.children[0];
            if (background) {
                background.width(canvasWidth);
                background.height(canvasHeight);
            }
            
            // 重新绘制
            stage.batchDraw();
        }
        
        // 工具切换
        function setTool(tool) {
            currentTool = tool;
            
            // 更新按钮状态
            document.querySelectorAll('.tool-button').forEach(btn => {
                btn.classList.remove('active');
            });
            event.target.classList.add('active');
            
            // 显示或隐藏图形选择组
            const shapeGroup = document.getElementById('shapeGroup');
            if (tool === 'polygon') {
                shapeGroup.style.display = 'flex';
            } else {
                shapeGroup.style.display = 'none';
            }
            
            // 重置状态
            isDrawing = false;
            isErasing = false;
            isSelecting = false;
            isTextEditing = false;
            polygonPoints = [];
            
            if (polygonLine) {
                polygonLine.destroy();
                polygonLine = null;
            }
            
            if (selectionRect) {
                selectionRect.destroy();
                selectionRect = null;
            }
            
            // 清除选中状态
            selectedShapes.forEach(shape => {
                // 恢复原始颜色和粗细
                if (shape.originalStroke) {
                    shape.stroke(shape.originalStroke);
                    shape.strokeWidth(shape.originalStrokeWidth);
                }
            });
            selectedShapes = [];
            document.getElementById('deleteBtn').style.display = 'none';
            
            // 隐藏所有文字控制按钮
            hideAllTextControls();
            
            // 确保文字元素保持可拖拽
            textElements.forEach(item => {
                if (item.element) {
                    item.element.draggable(true);
                }
            });
            
            stage.draggable(false);
        }
        
        // 鼠标/触摸按下事件
        function onMouseDown(e) {
            const pos = stage.getPointerPosition();
            if (!pos) return; // 防止无效位置
            
            switch (currentTool) {
                case 'brush':
                    isDrawing = true;
                    const brushLine = new Konva.Line({
                        id: generateShapeId(),
                        points: [pos.x, pos.y],
                        stroke: currentColor,
                        strokeWidth: currentBrushSize,
                        lineCap: 'round',
                        lineJoin: 'round',
                        tension: 0.5
                    });
                    layer.add(brushLine);
                    break;
                    
                case 'eraser':
                    isErasing = true;
                    eraseAt(pos);
                    break;
                    
                case 'select':
                    isSelecting = true;
                    const startPos = pos;
                    selectionRect = new Konva.Rect({
                        x: startPos.x,
                        y: startPos.y,
                        width: 0,
                        height: 0,
                        stroke: '#00ff00',
                        strokeWidth: 2,
                        dash: [5, 5]
                    });
                    layer.add(selectionRect);
                    break;
            }
        }
        

        
        // 鼠标抬起事件
        function onMouseUp(e) {
            if (isDrawing) {
                const lastLine = layer.children[layer.children.length - 1];
                if (lastLine && lastLine.points().length > 2) {
                    saveAction({
                        type: 'add_shape',
                        shapeId: lastLine.id(),
                        shapeData: lastLine.toJSON()
                    });
                }
            }
            
            if (isErasing && eraserPath) {
                const pathId = generateShapeId();
                eraserPath.id(pathId);
                saveAction({
                    type: 'eraser_action',
                    pathId: pathId,
                    pathData: eraserPath.toJSON()
                });
                resetEraserPath();
            }
            
            if (isSelecting && currentTool === 'select' && selectionRect) {
                // 框选完成后，查找选中的形状
                findSelectedShapes();
            }
            
            isDrawing = false;
            isErasing = false;
            isSelecting = false;
        }
        
        // 鼠标/触摸点击事件
        function onMouseClick(e) {
            const pos = stage.getPointerPosition();
            
            if (currentTool === 'polygon') {
                if (pos) {
                    addPolygonPoint(pos);
                }
            } else if (currentTool === 'text') {
                if (pos) {
                    // 检查是否点击了现有文字
                    const clickedText = findClickedText(pos);
                    if (clickedText) {
                        showTextControls(clickedText);
                    } else {
                        // 直接创建文字输入框
                        createTextInput(pos);
                    }
                }
                
                // 调试信息
                if (pos) {
                    console.log('Text tool click at:', pos);
                    const clickedText = findClickedText(pos);
                    console.log('Clicked text:', clickedText);
                }
            }
        }
        
        // 鼠标双击事件
        function onMouseDoubleClick(e) {
            if (currentTool === 'polygon' && polygonPoints.length >= 3) {
                completePolygon();
            }
        }
        
        // 查找选中的形状
        function findSelectedShapes() {
            if (!selectionRect) return;
            
            const selectionBounds = {
                x: selectionRect.x(),
                y: selectionRect.y(),
                width: selectionRect.width(),
                height: selectionRect.height()
            };
            
            // 确保选择框是正向的（从左到右，从上到下）
            if (selectionBounds.width < 0) {
                selectionBounds.x += selectionBounds.width;
                selectionBounds.width = Math.abs(selectionBounds.width);
            }
            if (selectionBounds.height < 0) {
                selectionBounds.y += selectionBounds.height;
                selectionBounds.height = Math.abs(selectionBounds.height);
            }
            
            selectedShapes = [];
            const shapes = layer.children.slice();
            
            shapes.forEach(shape => {
                if ((shape instanceof Konva.Line || shape instanceof Konva.Circle) && shape !== selectionRect) {
                    let isSelected = false;
                    
                    if (shape instanceof Konva.Line) {
                        const points = shape.points();
                        // 检查线条的每个点是否在选择框内
                        for (let i = 0; i < points.length; i += 2) {
                            const x = points[i];
                            const y = points[i + 1];
                            
                            if (x >= selectionBounds.x && x <= selectionBounds.x + selectionBounds.width &&
                                y >= selectionBounds.y && y <= selectionBounds.y + selectionBounds.height) {
                                isSelected = true;
                                break;
                            }
                        }
                    } else if (shape instanceof Konva.Circle) {
                        // 检查圆形是否与选择框相交
                        const circleX = shape.x();
                        const circleY = shape.y();
                        const radius = shape.radius();
                        
                        // 检查圆心是否在选择框内，或者圆形是否与选择框相交
                        const closestX = Math.max(selectionBounds.x, Math.min(circleX, selectionBounds.x + selectionBounds.width));
                        const closestY = Math.max(selectionBounds.y, Math.min(circleY, selectionBounds.y + selectionBounds.height));
                        
                        const distance = Math.sqrt((circleX - closestX) ** 2 + (circleY - closestY) ** 2);
                        if (distance <= radius) {
                            isSelected = true;
                        }
                    }
                    
                    if (isSelected) {
                        selectedShapes.push(shape);
                        // 保存原始颜色和粗细
                        shape.originalStroke = shape.stroke();
                        shape.originalStrokeWidth = shape.strokeWidth();
                        // 高亮选中的形状
                        shape.stroke('#ff0000');
                        shape.strokeWidth(shape.strokeWidth() + 2);
                    }
                }
            });
            
            // 显示或隐藏删除按钮
            const deleteBtn = document.getElementById('deleteBtn');
            if (selectedShapes.length > 0) {
                deleteBtn.style.display = 'inline-block';
            } else {
                deleteBtn.style.display = 'none';
            }
            
            layer.batchDraw();
        }
        
        // 添加多边形顶点
        function addPolygonPoint(pos) {
            polygonPoints.push(pos);
            
            if (polygonLine) {
                polygonLine.destroy();
            }
            
            const points = [];
            polygonPoints.forEach(point => {
                points.push(point.x, point.y);
            });
            
            polygonLine = new Konva.Line({
                points: points,
                stroke: currentColor,
                strokeWidth: currentBrushSize,
                closed: false
            });
            layer.add(polygonLine);
            layer.batchDraw();
        }
        
        // 完成多边形
        function completePolygon() {
            if (polygonPoints.length >= 3) {
                const points = [];
                polygonPoints.forEach(point => {
                    points.push(point.x, point.y);
                });
                
                const polygon = new Konva.Line({
                    id: generateShapeId(),
                    points: points,
                    stroke: currentColor,
                    strokeWidth: currentBrushSize,
                    closed: true,
                    fill: currentColor + '40' // 半透明填充
                });
                
                layer.add(polygon);
                polygonLine.destroy();
                polygonLine = null;
                polygonPoints = [];
                layer.batchDraw();
                
                saveAction({
                    type: 'add_shape',
                    shapeId: polygon.id(),
                    shapeData: polygon.toJSON()
                });
            }
        }
        
        // 橡皮擦功能 - 使用路径实现，减少数据量
        let eraserLayer;
        let eraserPath;
        
        function initEraserLayer() {
            // 创建专门的橡皮擦层
            eraserLayer = new Konva.Layer();
            stage.add(eraserLayer);
        }
        
        function eraseAt(pos) {
            const eraserSize = currentBrushSize * 2;
            
            if (!eraserPath) {
                // 创建橡皮擦路径
                eraserPath = new Konva.Line({
                    points: [pos.x, pos.y],
                    stroke: 'white',
                    strokeWidth: eraserSize * 2,
                    lineCap: 'round',
                    lineJoin: 'round',
                    tension: 0.5
                });
                eraserLayer.add(eraserPath);
            } else {
                // 添加点到现有路径
                const points = eraserPath.points();
                points.push(pos.x, pos.y);
                eraserPath.points(points);
            }
        }
        
        // 清理橡皮擦层
        function clearEraserLayer() {
            if (eraserLayer) {
                eraserLayer.destroyChildren();
                eraserPath = null;
            }
        }
        
        // 重置橡皮擦路径
        function resetEraserPath() {
            eraserPath = null;
        }
        
        // 存储橡皮擦轨迹
        let eraserTrail = [];
        
        // 鼠标/触摸移动时记录橡皮擦轨迹
        function onMouseMove(e) {
            const pos = stage.getPointerPosition();
            if (!pos) return; // 防止无效位置
            
            if (isDrawing && currentTool === 'brush') {
                const lastLine = layer.children[layer.children.length - 1];
                const newPoints = lastLine.points().concat([pos.x, pos.y]);
                lastLine.points(newPoints);
                layer.batchDraw();
            }
            
            if (isErasing && currentTool === 'eraser') {
                // 记录橡皮擦轨迹
                eraserTrail.push(pos);
                if (eraserTrail.length > 10) {
                    eraserTrail.shift();
                }
                
                // 擦除当前点
                eraseAt(pos);
                
                // 擦除轨迹上的点，实现连续擦除效果
                for (let i = 0; i < eraserTrail.length - 1; i++) {
                    const start = eraserTrail[i];
                    const end = eraserTrail[i + 1];
                    const steps = Math.ceil(Math.sqrt((end.x - start.x) ** 2 + (end.y - start.y) ** 2) / 2);
                    
                    for (let j = 1; j < steps; j++) {
                        const t = j / steps;
                        const interpPos = {
                            x: start.x + (end.x - start.x) * t,
                            y: start.y + (end.y - start.y) * t
                        };
                        eraseAt(interpPos);
                    }
                }
            }
            
            if (isSelecting && currentTool === 'select' && selectionRect) {
                const startPos = selectionRect.position();
                selectionRect.width(pos.x - startPos.x);
                selectionRect.height(pos.y - startPos.y);
                layer.batchDraw();
            }
        }
        

        
        // 删除选中的形状
        function deleteSelectedShapes() {
            const deletedShapes = [];
            
            selectedShapes.forEach(shape => {
                deletedShapes.push({
                    shapeId: shape.id(),
                    shapeData: shape.toJSON()
                });
                shape.destroy();
            });
            
            selectedShapes = [];
            
            // 隐藏删除按钮
            document.getElementById('deleteBtn').style.display = 'none';
            
            // 删除选择框
            if (selectionRect) {
                selectionRect.destroy();
                selectionRect = null;
            }
            
            layer.batchDraw();
            
            // 为每个删除的形状记录操作
            deletedShapes.forEach(item => {
                saveAction({
                    type: 'remove_shape',
                    shapeId: item.shapeId,
                    shapeData: item.shapeData
                });
            });
        }
        
        // 更新颜色
        function updateColor() {
            currentColor = document.getElementById('colorPicker').value;
        }
        
        // 更新画笔粗细
        function updateBrushSize() {
            currentBrushSize = parseInt(document.getElementById('brushSize').value);
            document.getElementById('brushSizeValue').textContent = currentBrushSize;
        }
        
        // 清空画布
        function clearCanvas() {
            // 保存当前所有形状和文字的数据
            const shapesData = [];
            layer.children.forEach(shape => {
                shapesData.push(shape.toJSON());
            });
            
            // 隐藏所有文字控制按钮
            hideAllTextControls();
            
            layer.destroyChildren();
            if (eraserLayer) {
                eraserLayer.destroyChildren();
            }
            
            // 清空文字元素数组
            textElements = [];
            
            layer.batchDraw();
            
            saveAction({
                type: 'clear_canvas',
                shapesData: shapesData
            });
        }
        
        // 撤销
        function undo() {
            if (historyIndex > 0) {
                const action = history[historyIndex];
                historyIndex--;
                applyHistoryAction(action, true);
                updateUndoRedoButtons();
            }
        }
        
        // 重做
        function redo() {
            if (historyIndex < history.length - 1) {
                historyIndex++;
                const action = history[historyIndex];
                applyHistoryAction(action, false);
                updateUndoRedoButtons();
            }
        }
        
        // 更新撤销/重做按钮状态
        function updateUndoRedoButtons() {
            const undoBtn = document.getElementById('undoBtn');
            const redoBtn = document.getElementById('redoBtn');
            
            undoBtn.disabled = historyIndex <= 0;
            redoBtn.disabled = historyIndex >= history.length - 1;
            
            // 调试信息
            console.log(`History: ${history.length} actions, current index: ${historyIndex}`);
            console.log(`Undo enabled: ${!undoBtn.disabled}, Redo enabled: ${!redoBtn.disabled}`);
        }
        
        // 保存操作记录
        function saveAction(action) {
            // 删除当前状态之后的历史记录
            history = history.slice(0, historyIndex + 1);
            
            // 添加操作记录
            history.push(action);
            historyIndex++;
            
            // 限制历史记录数量
            if (history.length > maxHistorySize) {
                history.shift();
                historyIndex--;
            }
            
            updateUndoRedoButtons();
        }
        
        // 应用历史操作
        function applyHistoryAction(action, isUndo) {
            switch (action.type) {
                case 'add_shape':
                    if (isUndo) {
                        // 撤销添加形状 = 删除形状
                        removeShapeById(action.shapeId);
                    } else {
                        // 重做添加形状 = 重新添加形状
                        addShapeFromData(action.shapeData);
                    }
                    break;
                    
                case 'remove_shape':
                    if (isUndo) {
                        // 撤销删除形状 = 重新添加形状
                        addShapeFromData(action.shapeData);
                    } else {
                        // 重做删除形状 = 再次删除形状
                        removeShapeById(action.shapeId);
                    }
                    break;
                    
                case 'clear_canvas':
                    if (isUndo) {
                        // 撤销清空画布 = 恢复所有形状
                        restoreShapesFromData(action.shapesData);
                    } else {
                        // 重做清空画布 = 再次清空
                        clearAllShapes();
                    }
                    break;
                    
                case 'eraser_action':
                    if (isUndo) {
                        // 撤销橡皮擦 = 删除橡皮擦路径
                        removeEraserPath(action.pathId);
                    } else {
                        // 重做橡皮擦 = 重新添加橡皮擦路径
                        addEraserPath(action.pathData);
                    }
                    break;
                    
                case 'add_text':
                    if (isUndo) {
                        // 撤销添加文字 = 删除文字
                        removeTextById(action.textId);
                    } else {
                        // 重做添加文字 = 重新添加文字
                        addTextFromData(action.textData);
                    }
                    break;
                    
                case 'remove_text':
                    if (isUndo) {
                        // 撤销删除文字 = 重新添加文字
                        addTextFromData(action.textData);
                    } else {
                        // 重做删除文字 = 再次删除文字
                        removeTextById(action.textId);
                    }
                    break;
                    
                case 'edit_text':
                    if (isUndo) {
                        // 撤销编辑文字 = 恢复原始内容
                        restoreTextData(action.textId, action.originalData);
                    } else {
                        // 重做编辑文字 = 应用新内容
                        restoreTextData(action.textId, action.newData);
                    }
                    break;
            }
        }
        
        // 形状管理函数
        function generateShapeId() {
            return 'shape_' + (++shapeIdCounter);
        }
        
        function addShapeFromData(shapeData) {
            const shape = Konva.Node.create(shapeData);
            layer.add(shape);
            layer.batchDraw();
        }
        
        function removeShapeById(shapeId) {
            const shape = layer.findOne('#' + shapeId);
            if (shape) {
                shape.destroy();
                layer.batchDraw();
            }
        }
        
        function clearAllShapes() {
            layer.destroyChildren();
            layer.batchDraw();
        }
        
        function restoreShapesFromData(shapesData) {
            shapesData.forEach(shapeData => {
                const shape = Konva.Node.create(shapeData);
                layer.add(shape);
            });
            layer.batchDraw();
        }
        
        function addEraserPath(pathData) {
            const path = Konva.Node.create(pathData);
            eraserLayer.add(path);
            eraserLayer.batchDraw();
        }
        
        function removeEraserPath(pathId) {
            const path = eraserLayer.findOne('#' + pathId);
            if (path) {
                path.destroy();
                eraserLayer.batchDraw();
            }
        }
        
        // 文字管理函数
        function addTextFromData(textData) {
            const textNode = Konva.Node.create(textData);
            
            // 确保文字可以拖拽
            textNode.draggable(true);
            
            // 添加点击事件监听
            textNode.on('click', function(e) {
                if (currentTool === 'text') {
                    e.cancelBubble = true; // 阻止事件冒泡
                    showTextControls(textNode);
                }
            });
            
            // 添加鼠标悬停效果
            textNode.on('mouseenter', function() {
                if (currentTool === 'text') {
                    document.body.style.cursor = 'pointer';
                }
            });
            
            textNode.on('mouseleave', function() {
                if (currentTool === 'text') {
                    document.body.style.cursor = 'default';
                }
            });
            
            // 添加拖拽事件监听
            textNode.on('dragmove', function() {
                if (textNode.controlsContainer) {
                    updateTextControlsPosition(textNode);
                }
            });
            
            textNode.on('dragend', function() {
                if (textNode.controlsContainer) {
                    updateTextControlsPosition(textNode);
                }
            });
            
            // 标记已添加拖拽监听器
            textNode._hasDragListeners = true;
            
            layer.add(textNode);
            
            // 添加到文字元素数组
            textElements.push({
                id: textNode.id(),
                element: textNode,
                data: textData
            });
            
            layer.batchDraw();
        }
        
        function removeTextById(textId) {
            const textNode = layer.findOne('#' + textId);
            if (textNode) {
                // 隐藏控制按钮和边框
                if (textNode.controlsContainer) {
                    if (textNode.controlsContainer.borderRect) {
                        textNode.controlsContainer.borderRect.destroy();
                    }
                    if (textNode.controlsContainer.deleteBtn) {
                        textNode.controlsContainer.deleteBtn.destroy();
                    }
                    if (textNode.controlsContainer.deleteText) {
                        textNode.controlsContainer.deleteText.destroy();
                    }
                    if (textNode.controlsContainer.editBtn) {
                        textNode.controlsContainer.editBtn.destroy();
                    }
                    if (textNode.controlsContainer.editText) {
                        textNode.controlsContainer.editText.destroy();
                    }
                    textNode.controlsContainer = null;
                }
                
                textNode.destroy();
                
                // 从文字元素数组中删除
                textElements = textElements.filter(item => item.id !== textId);
                
                layer.batchDraw();
            }
        }
        
        function restoreTextData(textId, textData) {
            const textNode = layer.findOne('#' + textId);
            if (textNode) {
                // 应用数据
                textNode.setAttrs(textData);
                
                // 更新文字元素数组中的数据
                const textElement = textElements.find(item => item.id === textId);
                if (textElement) {
                    textElement.data = textData;
                }
                
                layer.batchDraw();
            }
        }
        
        // 绘制预设图形
        function drawPresetShape(shapeType) {
            const centerX = stage.width() / 2;
            const centerY = stage.height() / 2;
            const size = Math.min(stage.width(), stage.height()) * 0.15;
            let points = [];
            
            switch (shapeType) {
                case 'square':
                    points = [
                        centerX - size/2, centerY - size/2,
                        centerX + size/2, centerY - size/2,
                        centerX + size/2, centerY + size/2,
                        centerX - size/2, centerY + size/2
                    ];
                    break;
                    
                case 'triangle':
                    points = [
                        centerX, centerY - size/2,
                        centerX - size/2, centerY + size/2,
                        centerX + size/2, centerY + size/2
                    ];
                    break;
                    
                case 'star':
                    points = generateStarPoints(centerX, centerY, size);
                    break;
                    
                case 'circle':
                    // 使用Konva的Circle而不是Line
                    const circle = new Konva.Circle({
                        id: generateShapeId(),
                        x: centerX,
                        y: centerY,
                        radius: size/2,
                        stroke: currentColor,
                        strokeWidth: currentBrushSize,
                        fill: currentColor + '40'
                    });
                    layer.add(circle);
                    layer.batchDraw();
                    
                    saveAction({
                        type: 'add_shape',
                        shapeId: circle.id(),
                        shapeData: circle.toJSON()
                    });
                    return;
            }
            
            const shape = new Konva.Line({
                id: generateShapeId(),
                points: points,
                stroke: currentColor,
                strokeWidth: currentBrushSize,
                closed: true,
                fill: currentColor + '40'
            });
            
            layer.add(shape);
            layer.batchDraw();
            
            saveAction({
                type: 'add_shape',
                shapeId: shape.id(),
                shapeData: shape.toJSON()
            });
        }
        
        // 生成五角星的点
        function generateStarPoints(centerX, centerY, size) {
            const points = [];
            const outerRadius = size / 2;
            const innerRadius = outerRadius * 0.4;
            const numPoints = 5;
            
            for (let i = 0; i < numPoints * 2; i++) {
                const angle = (i * Math.PI) / numPoints;
                const radius = i % 2 === 0 ? outerRadius : innerRadius;
                const x = centerX + radius * Math.cos(angle - Math.PI / 2);
                const y = centerY + radius * Math.sin(angle - Math.PI / 2);
                points.push(x, y);
            }
            
            return points;
        }
        
        // 查找点击的文字元素
        function findClickedText(pos) {
            // 获取舞台坐标
            const stagePos = stage.getPointerPosition();
            if (!stagePos) return null;
            
            // 查找所有文字元素
            const textNodes = layer.find('Text');
            
            for (let textNode of textNodes) {
                const textRect = textNode.getClientRect();
                
                // 检查点击位置是否在文字范围内（使用舞台坐标）
                if (stagePos.x >= textRect.x && stagePos.x <= textRect.x + textRect.width &&
                    stagePos.y >= textRect.y && stagePos.y <= textRect.y + textRect.height) {
                    return textNode;
                }
            }
            return null;
        }
        
        // 创建文字输入框
        function createTextInput(pos) {
            // 隐藏所有现有的文字控制按钮
            hideAllTextControls();
            
            // 获取画布在页面中的位置
            const stageRect = stage.container().getBoundingClientRect();
            
            // 创建文字输入框容器
            const textContainer = document.createElement('div');
            textContainer.className = 'text-input-overlay';
            
            // 计算输入框位置，考虑边框偏移
            const inputLeft = stageRect.left + pos.x - 2;
            const inputTop = stageRect.top + pos.y - 2;
            
            textContainer.style.left = inputLeft + 'px';
            textContainer.style.top = inputTop + 'px';
            textContainer.style.width = '100px'; // 初始宽度
            textContainer.style.height = '20px'; // 初始高度
            
            // 创建输入框
            const textInput = document.createElement('input');
            textInput.type = 'text';
            textInput.placeholder = '输入文字...';
            textInput.value = '';
            textInput.style.fontSize = '16px';
            textInput.style.fontFamily = 'Microsoft YaHei';
            textInput.style.color = currentColor;
            
            // 添加到容器
            textContainer.appendChild(textInput);
            document.body.appendChild(textContainer);
            
            // 聚焦输入框
            textInput.focus();
            
            // 保存当前输入框引用
            currentTextInput = textContainer;
            isTextEditing = true;
            
            // 使用标志防止重复调用
            let isFinishing = false;
            
            // 监听完成输入事件
            textInput.addEventListener('blur', function() {
                if (!isFinishing) {
                    isFinishing = true;
                    finishTextInput();
                }
            });
            
            textInput.addEventListener('keydown', function(e) {
                if (e.key === 'Enter' && !isFinishing) {
                    isFinishing = true;
                    finishTextInput();
                } else if (e.key === 'Escape' && !isFinishing) {
                    isFinishing = true;
                    cancelTextInput();
                }
            });
            
            // 监听输入事件，自动调整输入框大小
            textInput.addEventListener('input', function() {
                const canvas = document.createElement('canvas');
                const ctx = canvas.getContext('2d');
                ctx.font = '16px Microsoft YaHei';
                const textWidth = ctx.measureText(textInput.value || textInput.placeholder).width;
                const newWidth = Math.max(100, textWidth + 20); // 最小宽度100px，加上一些padding
                textContainer.style.width = newWidth + 'px';
            });
        }
        
        // 完成文字输入
        function finishTextInput() {
            if (!currentTextInput) return;
            
            const textInput = currentTextInput.querySelector('input');
            const text = textInput.value.trim();
            
            if (text) {
                // 获取画布在页面中的位置
                const stageRect = stage.container().getBoundingClientRect();
                
                // 计算文字在画布中的位置，考虑边框偏移
                const textX = parseInt(currentTextInput.style.left) - stageRect.left + 2;
                const textY = parseInt(currentTextInput.style.top) - stageRect.top + 2;
                
                // 创建Konva文字对象
                const textNode = new Konva.Text({
                    id: generateShapeId(),
                    x: textX,
                    y: textY,
                    text: text,
                    fontSize: 16,
                    fontFamily: 'Microsoft YaHei',
                    fill: currentColor,
                    draggable: true
                });
                
                // 添加点击事件监听
                textNode.on('click', function(e) {
                    if (currentTool === 'text') {
                        e.cancelBubble = true; // 阻止事件冒泡
                        showTextControls(textNode);
                    }
                });
                
                // 添加鼠标悬停效果
                textNode.on('mouseenter', function() {
                    if (currentTool === 'text') {
                        document.body.style.cursor = 'pointer';
                    }
                });
                
                textNode.on('mouseleave', function() {
                    if (currentTool === 'text') {
                        document.body.style.cursor = 'default';
                    }
                });
                
                // 添加拖拽事件监听
                textNode.on('dragmove', function() {
                    if (textNode.controlsContainer) {
                        updateTextControlsPosition(textNode);
                    }
                });
                
                textNode.on('dragend', function() {
                    if (textNode.controlsContainer) {
                        updateTextControlsPosition(textNode);
                    }
                });
                
                // 添加到画布
                layer.add(textNode);
                layer.batchDraw();
                
                // 保存到文字元素数组
                textElements.push({
                    id: textNode.id(),
                    element: textNode,
                    data: textNode.toJSON()
                });
                
                // 保存操作到历史记录
                saveAction({
                    type: 'add_text',
                    textId: textNode.id(),
                    textData: textNode.toJSON()
                });
            }
            
            // 清理输入框
            if (currentTextInput && currentTextInput.parentNode) {
                document.body.removeChild(currentTextInput);
            }
            currentTextInput = null;
            isTextEditing = false;
        }
        
        // 取消文字输入
        function cancelTextInput() {
            if (currentTextInput && currentTextInput.parentNode) {
                document.body.removeChild(currentTextInput);
                currentTextInput = null;
                isTextEditing = false;
            }
        }
        
        // 显示文字控制按钮
        function showTextControls(textNode) {
            // 隐藏所有其他控制按钮
            hideAllTextControls();
            
            // 确保文字可以拖拽
            textNode.draggable(true);
            
            // 获取文字位置和尺寸
            const textRect = textNode.getClientRect();
            
            // 创建选中边框（在canvas中绘制）
            const borderRect = new Konva.Rect({
                x: textRect.x - 2,
                y: textRect.y - 2,
                width: textRect.width + 4,
                height: textRect.height + 4,
                stroke: '#999',
                strokeWidth: 2,
                cornerRadius: 3,
                fill: 'transparent',
                listening: false // 不监听事件，避免干扰文字拖拽
            });
            
            // 创建删除按钮（左侧）
            const deleteBtn = new Konva.Circle({
                x: textRect.x - 15,
                y: textRect.y + textRect.height / 2,
                radius: 12,
                fill: '#dc3545',
                stroke: '#c82333',
                strokeWidth: 1
            });
            
            const deleteText = new Konva.Text({
                x: textRect.x - 15 - 6,
                y: textRect.y + textRect.height / 2 - 8,
                text: '×',
                fontSize: 16,
                fill: 'white',
                fontFamily: 'Arial'
            });
            
            // 创建编辑按钮（右侧）
            const editBtn = new Konva.Circle({
                x: textRect.x + textRect.width + 15,
                y: textRect.y + textRect.height / 2,
                radius: 12,
                fill: '#007bff',
                stroke: '#0056b3',
                strokeWidth: 1
            });
            
            const editText = new Konva.Text({
                x: textRect.x + textRect.width + 15 - 6,
                y: textRect.y + textRect.height / 2 - 8,
                text: '✎',
                fontSize: 14,
                fill: 'white',
                fontFamily: 'Arial'
            });
            
            // 添加点击事件
            deleteBtn.on('click', function(e) {
                e.cancelBubble = true;
                deleteTextNode(textNode);
            });
            deleteText.on('click', function(e) {
                e.cancelBubble = true;
                deleteTextNode(textNode);
            });
            
            editBtn.on('click', function(e) {
                e.cancelBubble = true;
                editTextNode(textNode);
            });
            editText.on('click', function(e) {
                e.cancelBubble = true;
                editTextNode(textNode);
            });
            
            // 添加到画布（确保文字在最上层）
            layer.add(borderRect);
            layer.add(deleteBtn);
            layer.add(deleteText);
            layer.add(editBtn);
            layer.add(editText);
            
            // 确保文字在最上层，可以接收拖拽事件
            textNode.moveToTop();
            
            // 保存引用
            textNode.controlsContainer = { 
                borderRect, 
                deleteBtn, 
                deleteText, 
                editBtn, 
                editText 
            };
            
            // 确保拖拽事件监听器存在（不重复绑定）
            if (!textNode._hasDragListeners) {
                textNode.on('dragmove', function() {
                    if (textNode.controlsContainer) {
                        updateTextControlsPosition(textNode);
                    }
                });
                
                textNode.on('dragend', function() {
                    if (textNode.controlsContainer) {
                        updateTextControlsPosition(textNode);
                    }
                });
                
                textNode._hasDragListeners = true;
            }
            
            layer.batchDraw();
        }
        
        // 更新文字控制元素位置
        function updateTextControlsPosition(textNode) {
            if (!textNode.controlsContainer) return;
            
            const textRect = textNode.getClientRect();
            
            // 更新边框位置
            if (textNode.controlsContainer.borderRect) {
                textNode.controlsContainer.borderRect.x(textRect.x - 2);
                textNode.controlsContainer.borderRect.y(textRect.y - 2);
                textNode.controlsContainer.borderRect.width(textRect.width + 4);
                textNode.controlsContainer.borderRect.height(textRect.height + 4);
            }
            
            // 更新删除按钮位置
            if (textNode.controlsContainer.deleteBtn) {
                textNode.controlsContainer.deleteBtn.x(textRect.x - 15);
                textNode.controlsContainer.deleteBtn.y(textRect.y + textRect.height / 2);
            }
            
            if (textNode.controlsContainer.deleteText) {
                textNode.controlsContainer.deleteText.x(textRect.x - 15 - 6);
                textNode.controlsContainer.deleteText.y(textRect.y + textRect.height / 2 - 8);
            }
            
            // 更新编辑按钮位置
            if (textNode.controlsContainer.editBtn) {
                textNode.controlsContainer.editBtn.x(textRect.x + textRect.width + 15);
                textNode.controlsContainer.editBtn.y(textRect.y + textRect.height / 2);
            }
            
            if (textNode.controlsContainer.editText) {
                textNode.controlsContainer.editText.x(textRect.x + textRect.width + 15 - 6);
                textNode.controlsContainer.editText.y(textRect.y + textRect.height / 2 - 8);
            }
            
            layer.batchDraw();
        }
        
        // 隐藏所有文字控制按钮
        function hideAllTextControls() {
            textElements.forEach(item => {
                if (item.element.controlsContainer) {
                    // 移除边框
                    if (item.element.controlsContainer.borderRect) {
                        item.element.controlsContainer.borderRect.destroy();
                    }
                    // 移除删除按钮
                    if (item.element.controlsContainer.deleteBtn) {
                        item.element.controlsContainer.deleteBtn.destroy();
                    }
                    if (item.element.controlsContainer.deleteText) {
                        item.element.controlsContainer.deleteText.destroy();
                    }
                    // 移除编辑按钮
                    if (item.element.controlsContainer.editBtn) {
                        item.element.controlsContainer.editBtn.destroy();
                    }
                    if (item.element.controlsContainer.editText) {
                        item.element.controlsContainer.editText.destroy();
                    }
                    item.element.controlsContainer = null;
                }
            });
            layer.batchDraw();
        }
        
        // 编辑文字
        function editTextNode(textNode) {
            // 隐藏控制按钮和边框
            if (textNode.controlsContainer) {
                if (textNode.controlsContainer.borderRect) {
                    textNode.controlsContainer.borderRect.destroy();
                }
                if (textNode.controlsContainer.deleteBtn) {
                    textNode.controlsContainer.deleteBtn.destroy();
                }
                if (textNode.controlsContainer.deleteText) {
                    textNode.controlsContainer.deleteText.destroy();
                }
                if (textNode.controlsContainer.editBtn) {
                    textNode.controlsContainer.editBtn.destroy();
                }
                if (textNode.controlsContainer.editText) {
                    textNode.controlsContainer.editText.destroy();
                }
                textNode.controlsContainer = null;
                layer.batchDraw();
            }
            
            // 获取文字位置和尺寸
            const textRect = textNode.getClientRect();
            const stagePos = stage.container().getBoundingClientRect();
            
            // 创建编辑输入框
            const editContainer = document.createElement('div');
            editContainer.className = 'text-input-overlay';
            
            // 计算编辑框位置，与显示的控制边框位置一致
            const editLeft = stagePos.left + textRect.x - 2;
            const editTop = stagePos.top + textRect.y - 2;
            
            editContainer.style.left = editLeft + 'px';
            editContainer.style.top = editTop + 'px';
            editContainer.style.width = (textRect.width + 4) + 'px';
            editContainer.style.height = (textRect.height + 4) + 'px';
            
            const editInput = document.createElement('input');
            editInput.type = 'text';
            editInput.value = textNode.text();
            editInput.style.fontSize = textNode.fontSize() + 'px';
            editInput.style.fontFamily = textNode.fontFamily();
            editInput.style.color = textNode.fill();
            
            editContainer.appendChild(editInput);
            document.body.appendChild(editContainer);
            
            // 聚焦并选择所有文字
            editInput.focus();
            editInput.select();
            
            // 保存当前编辑状态
            currentTextInput = editContainer;
            isTextEditing = true;
            
            // 使用标志防止重复调用
            let isFinishing = false;
            
            // 监听完成编辑事件
            editInput.addEventListener('blur', function() {
                if (!isFinishing) {
                    isFinishing = true;
                    finishTextEdit(textNode, editInput.value);
                }
            });
            
            editInput.addEventListener('keydown', function(e) {
                if (e.key === 'Enter' && !isFinishing) {
                    isFinishing = true;
                    finishTextEdit(textNode, editInput.value);
                } else if (e.key === 'Escape' && !isFinishing) {
                    isFinishing = true;
                    cancelTextEdit();
                }
            });
            
            // 监听输入事件，自动调整编辑框大小
            editInput.addEventListener('input', function() {
                const canvas = document.createElement('canvas');
                const ctx = canvas.getContext('2d');
                ctx.font = textNode.fontSize() + 'px ' + textNode.fontFamily();
                const textWidth = ctx.measureText(editInput.value).width;
                const newWidth = Math.max(textRect.width, textWidth + 20); // 至少保持原宽度
                editContainer.style.width = (newWidth + 4) + 'px';
            });
        }
        
        // 完成文字编辑
        function finishTextEdit(textNode, newText) {
            if (!currentTextInput) return;
            
            const trimmedText = newText.trim();
            if (trimmedText) {
                // 保存原始数据用于撤销
                const originalData = textNode.toJSON();
                
                // 更新文字内容
                textNode.text(trimmedText);
                layer.batchDraw();
                
                // 更新文字元素数组中的数据
                const textElement = textElements.find(item => item.id === textNode.id());
                if (textElement) {
                    textElement.data = textNode.toJSON();
                }
                
                // 保存编辑操作到历史记录
                saveAction({
                    type: 'edit_text',
                    textId: textNode.id(),
                    originalData: originalData,
                    newData: textNode.toJSON()
                });
            }
            
            // 清理编辑框
            if (currentTextInput && currentTextInput.parentNode) {
                document.body.removeChild(currentTextInput);
            }
            currentTextInput = null;
            isTextEditing = false;
        }
        
        // 取消文字编辑
        function cancelTextEdit() {
            if (currentTextInput && currentTextInput.parentNode) {
                document.body.removeChild(currentTextInput);
                currentTextInput = null;
                isTextEditing = false;
            }
        }
        
        // 删除文字
        function deleteTextNode(textNode) {
            // 隐藏控制按钮和边框
            if (textNode.controlsContainer) {
                if (textNode.controlsContainer.borderRect) {
                    textNode.controlsContainer.borderRect.destroy();
                }
                if (textNode.controlsContainer.deleteBtn) {
                    textNode.controlsContainer.deleteBtn.destroy();
                }
                if (textNode.controlsContainer.deleteText) {
                    textNode.controlsContainer.deleteText.destroy();
                }
                if (textNode.controlsContainer.editBtn) {
                    textNode.controlsContainer.editBtn.destroy();
                }
                if (textNode.controlsContainer.editText) {
                    textNode.controlsContainer.editText.destroy();
                }
                textNode.controlsContainer = null;
                layer.batchDraw();
            }
            
            // 保存删除的数据用于撤销
            const textData = textNode.toJSON();
            
            // 从画布中删除
            textNode.destroy();
            layer.batchDraw();
            
            // 从文字元素数组中删除
            textElements = textElements.filter(item => item.id !== textNode.id());
            
            // 保存删除操作到历史记录
            saveAction({
                type: 'remove_text',
                textId: textNode.id(),
                textData: textData
            });
        }
        
        // 键盘快捷键支持
        document.addEventListener('keydown', function(e) {
            // Ctrl+Z 或 Cmd+Z 撤销
            if ((e.ctrlKey || e.metaKey) && e.key === 'z' && !e.shiftKey) {
                e.preventDefault();
                undo();
            }
            // Ctrl+Y 或 Cmd+Y 重做
            if ((e.ctrlKey || e.metaKey) && e.key === 'y') {
                e.preventDefault();
                redo();
            }
            // Ctrl+Shift+Z 重做（macOS 习惯）
            if ((e.ctrlKey || e.metaKey) && e.key === 'z' && e.shiftKey) {
                e.preventDefault();
                redo();
            }
        });
        
        // 移动端优化：防止双击缩放
        document.addEventListener('touchstart', function(e) {
            if (e.touches.length > 1) {
                e.preventDefault();
            }
        }, { passive: false });
        
        document.addEventListener('touchend', function(e) {
            const now = Date.now();
            const lastTouch = document.lastTouch || 0;
            const timeDiff = now - lastTouch;
            
            if (timeDiff < 300 && timeDiff > 0) {
                e.preventDefault();
            }
            document.lastTouch = now;
        }, { passive: false });
        
        // 测试undo/redo功能
        function testUndoRedo() {
            console.log('=== Undo/Redo Test ===');
            console.log('Initial state:', { historyLength: history.length, historyIndex });
            
            // 绘制一个测试形状
            const testShape = new Konva.Line({
                id: generateShapeId(),
                points: [100, 100, 200, 200],
                stroke: 'red',
                strokeWidth: 5
            });
            layer.add(testShape);
            layer.batchDraw();
            
            saveAction({
                type: 'add_shape',
                shapeId: testShape.id(),
                shapeData: testShape.toJSON()
            });
            
            console.log('After adding shape:', { historyLength: history.length, historyIndex });
            
            // 测试撤销
            undo();
            console.log('After undo:', { historyLength: history.length, historyIndex });
            
            // 测试重做
            redo();
            console.log('After redo:', { historyLength: history.length, historyIndex });
        }
        
        // 测试文字功能
        function testTextFunction() {
            console.log('=== Testing Text Function ===');
            console.log('Current tool:', currentTool);
            console.log('Text elements:', textElements.length);
            textElements.forEach((item, index) => {
                console.log(`Text ${index}:`, item.element.text(), item.element.position());
                console.log(`Text ${index} draggable:`, item.element.draggable());
            });
        }
        
        // 测试拖拽功能
        function testDragFunction() {
            console.log('=== Testing Drag Function ===');
            if (textElements.length > 0) {
                const firstText = textElements[0].element;
                console.log('First text draggable:', firstText.draggable());
                console.log('First text position:', firstText.position());
                
                // 尝试手动设置拖拽
                firstText.draggable(true);
                console.log('After setting draggable:', firstText.draggable());
            }
        }
        
        // 初始化
        initCanvas();
    </script>
</body>
</html>
